const { PubSub } = require('apollo-server-koa')
const pubsub = new PubSub()
const SUB_ADD = 'SUB_ADD'

let todolist = []

const resolvers = {
    Query: {
        user: (_, args, { dataSources }) => {
            return { name: "asd" }
        },
        book: (_, { keywords }, { dataSources }) => {
            return dataSources.douBanAPI.getBook(keywords)
        },
        todolist: (_, args, ctx) => {
            return todolist
        }
    },
    Subscription: {
        subAdd: {
            subscribe: () => pubsub.asyncIterator([SUB_ADD])
        }
    },
    Mutation: {
        addTodo: (_, { todo }, ctx) => {
            todolist.push({ name: todo, status: Math.round(Math.random() * 3) })
            return todolist.slice(-1)[0]
        },
        delTodo: (_, { key }, ctx) => {
            return todolist.splice(key, 1)[0]
        }
    }
}

module.exports = { resolvers, pubsub, SUB_ADD }